package io.github.wslxm.springbootplus2.manage.sys.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.wslxm.springbootplus2.core.base.model.BasePage;
import io.github.wslxm.springbootplus2.core.base.service.impl.BaseServiceImpl;
import io.github.wslxm.springbootplus2.core.constant.SymbolConst;
import io.github.wslxm.springbootplus2.core.utils.XjBeanUtil;
import io.github.wslxm.springbootplus2.manage.sys.mapper.SysUserAkSkMapper;
import io.github.wslxm.springbootplus2.manage.sys.model.dto.SysUserAkSkDTO;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysUserAkSk;
import io.github.wslxm.springbootplus2.manage.sys.model.query.SysUserAkSkQuery;
import io.github.wslxm.springbootplus2.manage.sys.model.vo.SysUserAkSkVO;
import io.github.wslxm.springbootplus2.manage.sys.service.SysUserAkSkService;
import io.github.wslxm.springbootplus2.utils.XjSignMd5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * base--sys--用户管理 ServiceImpl
 *
 * <p>
 * ::本代码由[兮家小二]提供的代码生成器生成,如有问题,请手动修改 ::作者CSDN:https://blog.csdn.net/qq_41463655
 * </p>
 *
 * @author ws
 * @email 1720696548@qq.com
 * @date 2025-09-24 09:26:12
 */
@Service
public class SysUserAkSkServiceImpl extends BaseServiceImpl<SysUserAkSkMapper, SysUserAkSk> implements SysUserAkSkService {

    @Override
    public BasePage<SysUserAkSkVO> findPage(SysUserAkSkQuery query) {
        LambdaQueryWrapper<SysUserAkSk> queryWrapper = new LambdaQueryWrapper<SysUserAkSk>().orderByDesc(SysUserAkSk::getCreateTime);
        queryWrapper.eq(StringUtils.isNotBlank(query.getUserId()), SysUserAkSk::getUserId, query.getUserId());
        queryWrapper.eq(StringUtils.isNotBlank(query.getAccessKey()), SysUserAkSk::getAccessKey, query.getAccessKey());
        if (StringUtils.isNotBlank(query.getExpireTime()) && query.getExpireTime().split(SymbolConst.COMMA).length >= 1) {
            queryWrapper.between(SysUserAkSk::getExpireTime, query.getExpireTime().split(",")[0], query.getExpireTime().split(",")[1]);
        }
        Page<SysUserAkSk> page = this.page(new Page<>(query.getCurrent(), query.getSize()), queryWrapper);
        return XjBeanUtil.pageVo(page, SysUserAkSkVO.class);
    }

    @Override
    public SysUserAkSkVO findId(String id) {
        return XjBeanUtil.convert(this.getById(id), SysUserAkSkVO.class);
    }

    @Override
    public SysUserAkSkVO insert(SysUserAkSkDTO dto) {
        SysUserAkSk entity = dto.convert(SysUserAkSk.class);
        String ak = generateAccessKey("AK");
        String sk = generateSecretKey();
        entity.setAccessKey(ak);
        entity.setSecretKey(XjSignMd5Util.md5(sk));
        boolean b = this.save(entity);
        // ak/sk 仅创建时会返回明文sk
        SysUserAkSkVO vo = XjBeanUtil.convert(entity, SysUserAkSkVO.class);
        vo.setAccessKey(ak);
        vo.setSecretKey(sk);
        return vo;
    }

    @Override
    public boolean upd(String id, SysUserAkSkDTO dto) {
        SysUserAkSk entity = dto.convert(SysUserAkSk.class);
        entity.setId(id);
        return this.updateById(entity);
    }

    @Override
    public boolean del(String id) {
        return this.removeById(id);
    }


    /**
     * 生成 Access Key (AK)
     * 格式: AK_<24位大写字母+数字>
     */
    private static String generateAccessKey(String prefix) {
        String randomString = RandomUtil.randomString("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 24);
        return StrUtil.format("{}_{}", prefix, randomString);
    }


    /**
     * 生成 Secret Key (SK)
     * 使用 RandomUtil.randomBytes() 生成 32 字节安全随机数据
     */
    public static String generateSecretKey() {
        // ✅ 底层使用 SecureRandom
        byte[] randomBytes = RandomUtil.randomBytes(32);
        return Base64.encode(randomBytes)
                .replace("=", "")
                .replace("+", "0")
                .replace("/", "_");
    }
}
